package ar.com.miguelgriffa.secureproperties.ant;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.types.FileSet;

import ar.com.miguelgriffa.secureproperties.SecureProperties;

/**
 * ANT Task to encrypt a propery file
 * 
 * @author mgriffa
 */
public class Encrypt extends BaseTask {

	// TODO add key attribute when library supports it

	@Override
	public void execute() throws BuildException {
		if (secure != null) {
			if (secure.exists() && !overwrite) {
				throw new BuildException("Target file " + secure + " already exists, delete it or set attribute overwrite='true'");
			}
			encryptSingle(plain, secure);
		} else {
			if (filesets.isEmpty()) {
				throw new BuildException("secure is not set and no nested filset element was found");
			}
			for (FileSet fs : super.filesets) {
				DirectoryScanner ds = fs.getDirectoryScanner(getProject());
				ds.scan();
				String[] files = ds.getIncludedFiles();
				File basedir = ds.getBasedir();
				if (files!=null) {
					for (int i=0;i<files.length;i++) {
						File f = new File(basedir+File.separator+files[i]);
						encryptSingle(f, new File(f+".encrypted"));
					}
				}
			}
		}
	}

	private void encryptSingle(File src, File dst) {
		log("Encrypting "+src.getName()+" -> "+dst.getName());
		try {
			FileInputStream in = new FileInputStream(src);
			FileOutputStream out = new FileOutputStream(dst);

			Properties p1 = new Properties();
			p1.load(in);

			SecureProperties p2 = new SecureProperties();
			if (key != null) {
				p2.setKey(key);
			}
			p2.putAll(p1);
			p2.store(out, header);
			out.close();
		} catch (Exception e) {
			handleException(e);
		}
		if (verify) {
			verify(src, dst);
		}

	}

}
